package com.credit.mola.app.ui.process.activity

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.credit.mola.app.R
import com.credit.mola.app.adapter.ProcessStepAdapter
import com.credit.mola.app.databinding.ActivityProcessBinding
import com.credit.mola.app.pro.ProActivity
import com.credit.mola.app.ui.credit.activity.ApplyActivity
import com.credit.mola.app.ui.process.page.BindAccountPage
import com.credit.mola.app.ui.process.page.CommonPage
import com.credit.mola.app.ui.process.page.ContactPage
import com.credit.mola.app.ui.process.page.FacePage
import com.credit.mola.app.ui.process.page.OcrPage
import com.credit.mola.app.utils.BarUtils
import com.credit.mola.app.utils.SikadwaPickContactUtils
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.helper.SikadwaMainProcessHelper
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.IHttpCallback
import com.credit.mola.lib_baseadapter.SikadwaOnItemChildClickListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/23 10:43
 * @Annotation：流程列表页面
 */
class ProcessActivity : ProActivity() {
    private var _binding: ActivityProcessBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //选择联系人
    var pickContact: SikadwaPickContactUtils? = null
    private var mTabAdapter: ProcessStepAdapter? = null

    companion object {
        private const val INTENT_KEY_AMOUNT = "amount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, ProcessActivity::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }

    override fun getRootView(): View {
        _binding = ActivityProcessBinding.inflate(layoutInflater)
        return binding.root
    }

    @Subscribe
    override fun initView() {
        _binding?.parentLayout?.setPadding(0, BarUtils.getStatusBarHeight(),0,0)
        EventBus.getDefault().register(this)
        initRecyclerView()

        pickContact = SikadwaPickContactUtils(this)
    }

    override fun initListener() {
        //返回
        _binding?.imgBack?.setOnClickListener {
            finish()
        }
        //联系客服
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("Information Process " + _binding?.textTitle?.text.toString() + " Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER, "Information Process " + _binding?.textTitle?.text.toString() + " Page")
        }
        _binding?.btnNext?.setOnClickListener {
            //通知提交联系人 || 人脸 数据
            EventBus.getDefault().post(Configs.Event.PROCESS_DATA_SUB)
        }
    }

    override fun initData() {
        loadProcessStepAction()
    }

    /**
     * 初始化Tab列表
     */
    private fun initRecyclerView() {
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvStep?.layoutManager = layoutManager
        mTabAdapter = ProcessStepAdapter(_binding?.rvStep)
        _binding?.rvStep?.adapter = mTabAdapter
        _binding?.rvStep?.itemAnimator = DefaultItemAnimator()
        mTabAdapter?.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
        })
    }

    /**
     * 显示全部流程列表
     */
    private fun setProcessTabList(dataList: ArrayList<JSONObject>, selectIndex: Int) {
        mTabAdapter?.data = dataList
        if (selectIndex != -1) {
            _binding?.textTitle?.text = dataList[selectIndex].optString("tabTitle")
            _binding?.rvStep?.post {
                _binding?.rvStep?.smoothScrollToPosition(selectIndex)
            }
        }
    }

    /**
     * 常规通用样式
     */
    private fun showCommonPage(data: JSONObject?) {
        data?.let {
            //增加额度 = 外显额度 * 2.5%
            data.put("limitAmount", BigDecimal(getLimitAmount()).multiply(BigDecimal("0.025")).stripTrailingZeros().toPlainString())
            replaceContainerFragement(R.id.contentLayout, CommonPage(it))
        }
    }

    /**
     * Contact联系人样式
     */
    private fun showContactInfoPage(data: JSONObject?) {
        data?.let {
            //增加额度 = 外显额度 * 2.5%
            data.put("limitAmount", BigDecimal(getLimitAmount()).multiply(BigDecimal("0.025")).stripTrailingZeros().toPlainString())
            replaceContainerFragement(R.id.contentLayout, ContactPage(this,data))
        }
    }

    /**
     * 证件照样式
     */
    private fun showOcrInfoPage(data: JSONObject?) {
        data?.let {
            //增加额度 = 外显额度 * 5%
            data.put("limitAmount", BigDecimal(getLimitAmount()).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
            replaceContainerFragement(R.id.contentLayout, OcrPage(data))
        }
    }

    /**
     * 人脸自拍样式
     */
    private fun showSelfieInfoPage() {
        replaceContainerFragement(R.id.contentLayout, FacePage.newInstance {
            if (it.isEmpty()){
                binding.btnNext.text = getString(R.string.process_face_start)
            } else {
                binding.btnNext.text = getString(R.string.process_face_submit)
            }
        })
    }

    /**
     * 绑定账号（法语）
     */
    private fun showAccountInfoFrenchPage() {
        replaceContainerFragement(R.id.contentLayout, BindAccountPage())
    }

    /**
     * 进入贷款申请页面
     */
    private fun showApplyPage() {
        onIntent(ApplyActivity::class.java)
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        }, 500)
    }

    /**
     * 提交流程数据
     */
    fun submitAction(params: JSONObject) {
        showLoading()
        onSubmitProcessAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    fun showSubmitSuccess() {
        //通知刷新总流程
        EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            Configs.Event.PROCESS_REFRESHED -> {//总流程刷新完成
                loadProcessStepAction()
            }
        }
    }

    /**
     * 获取 steps 中第一个在步骤在总步骤中是第几个
     */
    private fun getStepIndex(): Int{
        var index = -1
        //剩余未完成步骤
        val stepList = SikadwaMainProcessHelper.takeSikadwaMainProcessStepList()
        if (stepList.size == 0){//已完成
            return index
        }
        //总步骤
        val allSteps = SikadwaMainProcessHelper.takeSikadwaMainProcessAllStepList()
        if (allSteps.size == 0){
            return index
        }
        //当前进行的步骤
        val curtStep = stepList[0]
        for (i in 0..< allSteps.size){
            if (curtStep == allSteps[i]){
                index = i
                break
            }
        }
        return index
    }

    /**
     * 获取额度
     */
    private fun getLimitAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 获取流程步骤列表
     */
    private fun loadProcessStepAction(){
        val allStepTitles = SikadwaMainProcessHelper.takeSikadwaMainProcessAllStepTitleList()
        val tabList = arrayListOf<JSONObject>()
        //当前进行的步骤
        val curtIndex = getStepIndex()
        for (i in 0 until allStepTitles.size) {
            val tabObj = JSONObject()
            tabObj.put("tabTitle", allStepTitles[i])
            tabObj.put("selectIndex", curtIndex)
            tabList.add(tabObj)
        }
        //设置所有步骤列表
        setProcessTabList(tabList,curtIndex)

        showStepPage()
    }

    /**
     * 根据Step类型显示不同的Page
     */
    private fun showStepPage(){
        //当前进行的步骤
        val curtIndex = getStepIndex()
        if (curtIndex == -1){//所有步骤已完成
            showApplyPage()
            return
        }
        val allSteps = SikadwaMainProcessHelper.takeSikadwaMainProcessAllStepList()
        //获取对应的key
        val curtKey = allSteps[curtIndex]

        val processData = SikadwaMainProcessHelper.takeSikadwaMainProcessData()
        processData?.let {
            //Contact 类型
            if (it.has(curtKey)){
                val stepData = it.optJSONObject(curtKey)
                stepData?.put("stepTitle",curtKey)
                if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                    showContactInfoPage(stepData)
                    return
                }
            }

            //todo Ocr证件照样式
            if (curtKey.contains("ocr_info")){
                val stepData = JSONObject()
                stepData.put("stepTitle",curtKey)
                showOcrInfoPage(stepData)
                return
            }

            //todo Selfie自拍照样式
            if (curtKey.contains("sefie_info")){
                showSelfieInfoPage()
                return
            }

            //todo Account账户样式（法语地区绑定账号）
            if (curtKey.contains("account_info") && Configs.isFrench()){
                showAccountInfoFrenchPage()
                return
            }
            //常规通用样式
            if (it.has(curtKey)){
                val stepData = it.optJSONObject(curtKey)
                stepData?.put("stepTitle",curtKey)
                showCommonPage(stepData)
            }
        }
    }

    /**
     * 提交流程数据
     */
    private fun onSubmitProcessAction(params: JSONObject) {
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showSubmitSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStop() {
        super.onStop()
        _binding?.root?.clearFocus()
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        EventBus.getDefault().unregister(this)
    }
}